<script setup lang="ts">
import {computed, onMounted, ref} from "vue";
import request from "@/utils/request.ts";
import {ElMessage, ElMessageBox} from "element-plus";
import {require} from "@/utils/getFileUrl.ts";
import {deleteGame} from "@/utils/deleteGame.ts";
import getNewPrices from "../utils/getNewPrices.ts";
let games=ref()


import { useRouter } from 'vue-router'
const router = useRouter()
// 跳转到支付页面
const goToPay = () => {
  if (totalAmount.value <= 0) {
    ElMessage.warning('购物车为空，无法支付')
    return
  }

  const totalPrice = totalAmount.value.toFixed(2)
  const subject = '购物车商品'

  const routeData = router.resolve({
    path: '/pay',
    query: { total: totalPrice, subject }
  })

  window.open(routeData.href, '_blank')
}


onMounted(() => {
  request.get("/getGameInShopping")
  .then((res) => {
    games.value=res.data
  })
  .catch(error=> {
    ElMessage.error( error)
  })
});
const totalAmount = computed(() => {
  if (!games.value || games.value.length === 0) return 0;
  return games.value.reduce((sum: number, game: any) => {
    const discountedPrice = getNewPrices(game.price, game.discount);
    return sum + parseFloat(discountedPrice);
  }, 0);
});

// 确认删除
const confirmDelete = (game) => {
  ElMessageBox.confirm(
      `确认删除游戏《${game.name}》？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(() => handleDelete(game))
      .catch(() => ElMessage.info('已取消删除'))
}
const handleDelete = async (game) => {
  try {
    await deleteGame(game.id)
    // 从本地列表中移除
    games.value = games.value.filter(item => item.id !== game.id)
    ElMessage.success('游戏已成功删除')
  } catch (error) {
    ElMessage.error(error.message)
  }
}

</script>

<template>
  <div class="content">
    <div class="game-item">
      <h2 class="cart-title">您的购物车</h2>
      <div class="single-game " v-for="(game,index) in games" :key="index">
        <img :src="require('@/assets/img/'+ game.img)" class="game-cover">
        <div class="game-info ">
          <h3 class="game-name">{{ game.name }}</h3>
          <div class="platforms">
            <span>Windows</span>
            <span>MacOS</span>
            <span>Linux</span>
          </div>
        </div>
        <div class="game-price">
          <span class="price">￥{{getNewPrices(game.price,game.discount)}}</span>
          <button class="remove-button" @click="confirmDelete(game)">Remove</button>
        </div>
      </div>
    </div>
    <div class="checkout-section myFlex-x" style="color: white">
      <div class="total-info myFlex-x">
        <p class="total-label">预计总额:</p>
        <p class="total-amount">¥{{totalAmount.toFixed(2)}}</p>
      </div>
      <button class="checkout-button" @click="goToPay">跳转至支付</button>

      <div class="license-info">
        <p>购买数字产品将会授予该产品在 huda 上的许可</p>
        <p>请参见 <a href="#" class="steam-link">huda 订户协议</a>，了解完整条款和条件。</p>
      </div>
    </div>
  </div>
</template>
<style scoped>
@import "../assets/css/shoppingCar.css";
</style>